//
//  SecondClassViewController.m
//  HuiMWorld
//
//  Created by chirui on 2018/1/11.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "SecondClassViewController.h"
#import "ClassListCell.h"
#import "ClassCollectionCell.h"
#import "ClassCollectionReusableView.h"
#import "ClassDetailsViewController.h"


@interface SecondClassViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UISearchBarDelegate> {
    
    UITableView * _tableView;
    NSArray * classListArray;
    UICollectionView * _collectionView;
    UILabel * titleLabel;
    int i;
    NSArray * netNavArray;
    NSArray * goodsArray;
    
    NSDictionary * dataDic;
    
    NSString * chooseCidStr;
    UIView * noBodyView;
    
    
}

@end

@implementation SecondClassViewController


- (void)viewDidLoad {
    [super viewDidLoad];


    
    i = 0;
    [self creatNavUi];
    [self creatTableView];
    [self creatCollectionView];
    
     [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img_nav_bg"] forBarMetrics:UIBarMetricsDefault];
    
    //    [_tableView selectRowAtIndexPath:ip animated:NO scrollPosition:UITableViewScrollPositionBottom];
    //    if (i==0) {
    //        [_tableView deselectRowAtIndexPath:ip animated:YES];
    //    }
     noBodyView = [NothingMessageView creatNothingMessageViewFrame:CGRectMake(100+(WIDTH-300)/2, (HEIGHT-64)/2-100, 200, 200) andMessageStr:@"还没有相关内容~" onView:nil];
    
    [self getDataRequest];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)creatNavUi {
    
    self.navigationItem.titleView=[TopLabel withLabelWithLabelText:@"分类"];
  
}

#pragma mark - 按钮的点击事件



-(void)creatTableView {
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,100, HEIGHT) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [UIView new];
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    _tableView.separatorStyle = NO;
 
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50.f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return netNavArray.count;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dic = netNavArray[indexPath.row];
    
    ClassListCell *   cell = [[[NSBundle mainBundle] loadNibNamed:[ClassListCell reuseIdentifier] owner:nil options:nil] lastObject];
    cell.titleLabel.text = dic[@"category_name"];
    if (i==0) {
        if (indexPath.row==i) {
            cell.titleLabel.backgroundColor =[UIColor whiteColor];
            cell.lineView.hidden =NO;
            
        }
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    i = (int)indexPath.row;
    [_tableView reloadData];
    ClassListCell *   cell_choose = [tableView cellForRowAtIndexPath:indexPath];
    cell_choose.lineView.hidden =NO;
    cell_choose.titleLabel.backgroundColor =[UIColor whiteColor];
    cell_choose.bgView.backgroundColor =[UIColor whiteColor];
    
    [_collectionView reloadData];

  
    //    if (indexPath.row!=0) {
    //        cell_choose.titleLabel.backgroundColor = Color(246, 247, 248);
    //         cell_choose.bgView.backgroundColor = Color(246, 247, 248);
    //    }
    
}

#pragma creatCollectionView

-(void)creatCollectionView {
    
    
    titleLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, WIDTH-100, 30)];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(100, 0,WIDTH-100,HEIGHT) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collectionView];
    _collectionView.showsVerticalScrollIndicator = NO;
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self getDataRequest];
    }];
    _collectionView.mj_header = header;
    
    //注册cell类
    [_collectionView registerNib:[UINib nibWithNibName:@"ClassCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"ClassCollectionCell"];
    
}

//设置段数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
//返回多少个item
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSDictionary * dic = netNavArray[i];
    goodsArray  = dic[@"children"];
    
    if (goodsArray.count>0) {
        noBodyView.hidden =YES;
      
    }else {
        noBodyView.hidden =NO;
        [self.view addSubview:noBodyView];
    }
    return goodsArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dic = goodsArray[indexPath.row];
    ClassCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ClassCollectionCell" forIndexPath:indexPath];
    cell.title.text = dic[@"category_name"];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:dic[@"cover_photo"]] placeholderImage:[UIImage imageNamed:@"moren_image"]];
    cell.clipsToBounds = NO;
    
    return cell;
}
//默认大小50*50
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //    第一个参数是宽，第二个参数是高
    
    CGSize size=CGSizeMake((WIDTH-100-40)/3, (WIDTH-100-40)/3 * 1.4);
    
    return size;
    //    横屏滑动时：（0，0）  最左边最上边  最左边最下边
    //    竖屏滑动时：（0，0）  最左边最上边  最右边最上边
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(10, 10, 5, 10);
}

//设置水平间隙   默认10
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

////设置垂直间隙  默认10
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return CGSizeMake(0, 0);
}
//设置footer的宽度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    //第一个参数：水平滑动时footer的宽度
    //第二个参数：垂直滑动时footer的高度
    return CGSizeMake(0, 0);
}

//选中的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NSMutableArray * array = [NSMutableArray new];
    
    if (array) {
        
        [array removeAllObjects];
    }
    
    NSDictionary * dic = netNavArray[i];
    
    NSDictionary * allDic = @{@"cate_id":dic[@"cate_id"],@"category_name":@"全部"};
    
    [array addObject:allDic];
    
    NSArray * ary = dic[@"children"];
    
    for (NSDictionary * dict in ary) {
        [array addObject:dict];
    }

    ClassDetailsViewController * class =[[ClassDetailsViewController alloc]init];
    class.titleArray = array;
    class.index = indexPath.row+1;
    class.titleStr = dic[@"category_name"];
    [self.navigationController pushViewController:class animated:YES];
    NSLog(@"点击的第%ld个商品",indexPath.row);
    
}

#pragma mark 网络请求


-(void)getDataRequest{
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_categoryList_api) andparameters:nil Success:^(id responseObject) {
        
        if (codeSucess) {
            
            if ([responseObject[@"datas"] isKindOfClass:[NSArray class]]) {
                
                  netNavArray = responseObject[@"datas"];
            }
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
        [_collectionView.mj_header endRefreshing];
        [_collectionView reloadData];
        [_tableView reloadData];
        
    } failed:^(NSError *error) {
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
}

@end
